import React, { useState, useEffect, useRef } from 'react'
import useStore from '../../components/useStore'
import { Button, Col, DatePicker, Divider, Form, Input, Modal, Row, Spin, Upload, notification, InputNumber, Radio, Select, Table, message, Pagination } from 'antd'
import { UploadOutlined, createFromIconfontCN, LinkOutlined, PlusOutlined, MinusOutlined } from '@ant-design/icons'
import dayjs from 'dayjs';
import request from '../../untils/request';

const IconFont = createFromIconfontCN({
  scriptUrl: require('../../../devDocument/icon.js'),
});

const UploadOrder = () => {
    const { collapsed, setnowroute } = useStore()
    const [form] = Form.useForm()
    
    // 状态管理
    const [businessContractFile, setBusinessContractFile] = useState(null)
    const [technicalAgreementFile, setTechnicalAgreementFile] = useState(null)
    const [uploading, setUploading] = useState(false)
    const [technicalUploadType, setTechnicalUploadType] = useState('file')
    const [businessUploadType, setBusinessUploadType] = useState('file')
    
    // 客户相关状态
    const [customerList, setCustomerList] = useState([]);
    const [loadingCustomers, setLoadingCustomers] = useState(false);
    
    // BOM搜索相关状态 - 为每个产品行单独维护搜索状态
    const [bomSearchState, setBomSearchState] = useState({});
    
    // 分页相关状态
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [totalCustomers, setTotalCustomers] = useState(0);
    const [searchName, setSearchName] = useState('');
    
    // 产品列表状态
    const [productList, setProductList] = useState([
        { key: '1', product_part_number: '', specification_and_model: '', quantity: 1 }
    ]);

    // 防抖计时器引用
    const debounceTimers = useRef({});
    // 客户搜索防抖计时器
    const customerSearchTimer = useRef(null);

    // 初始化产品行的搜索状态
    useEffect(() => {
        const initialState = {};
        productList.forEach(item => {
            initialState[item.key] = {
                keyword: '',
                results: [],
                loading: false
            };
        });
        setBomSearchState(initialState);
    }, []);

    // 确保页面加载时表单同步选中状态
    useEffect(() => {
        form.setFieldsValue({
            technical_upload_type: 'file',
            business_upload_type: 'file'
        });
    }, [form]);

    /**前往excel表格导入*/
    const toExcel = async () => {
        setnowroute({...{route:"/ship/sales/salesExcelForm",title:"excel导入销售订单"}})
    }

    // 获取客户列表数据
    const fetchCustomers = () => {
        const offset = (currentPage - 1) * pageSize;
        setLoadingCustomers(true);
        request("/admin/customer/getCustomers", {
            method: "POST",
            body: {
                pageSize,
                offset,
                name: searchName
            }
        }).then((res) => {
            setLoadingCustomers(false);
            if (res.code === 200) {
                setCustomerList(res.data || []);
                setTotalCustomers(res.total || 0);
            } else {
                notification.error({ message: '获取客户列表失败' });
            }
        }).catch(() => {
            setLoadingCustomers(false);
            notification.error({ message: '获取客户列表时发生错误' });
        });
    };

    // 搜索BOM（只搜索一级BOM）- 为每个产品行单独处理，添加防抖机制
    const searchFirstLevelBoms = (key, keyword) => {
        // 清除该产品行的旧计时器
        if (debounceTimers.current[key]) {
            clearTimeout(debounceTimers.current[key]);
        }
        
        // 更新当前行的搜索关键词
        setBomSearchState(prev => ({
            ...prev,
            [key]: {
                ...prev[key],
                keyword
            }
        }));
        
        // 关键词为空时清空结果
        if (!keyword.trim()) {
            setBomSearchState(prev => ({
                ...prev,
                [key]: {
                    ...prev[key],
                    results: [],
                    loading: false
                }
            }));
            return;
        }
        
        // 设置防抖，300ms内连续输入不会频繁触发请求
        debounceTimers.current[key] = setTimeout(() => {
            // 更新加载状态
            setBomSearchState(prev => ({
                ...prev,
                [key]: {
                    ...prev[key],
                    loading: true
                }
            }));
            
            // 只传递number参数进行搜索，避免参数冲突
            request("/admin/bom/getBom", {
                method: "POST",
                body: {
                    pageSize: 50,
                    offset: 0,
                    topLevel: true,   // 新增参数，表示只查询顶级BOM
                    number: keyword,  // 只按产品编号搜索
                }
            }).then((res) => {
                setBomSearchState(prev => ({
                    ...prev,
                    [key]: {
                        ...prev[key],
                        results: res.code === 200 ? (res.data?.list || []) : [],
                        loading: false
                    }
                }));
            }).catch(() => {
                setBomSearchState(prev => ({
                    ...prev,
                    [key]: {
                        ...prev[key],
                        loading: false
                    }
                }));
                notification.error({ message: '搜索BOM时发生错误' });
            });
        }, 300); // 300ms防抖
    };

    // 初始加载客户列表
    useEffect(() => {
        fetchCustomers();
    }, [currentPage, pageSize, searchName]);

    // 处理客户分页变化
    const handlePageChange = (page, pageSize) => {
        setCurrentPage(page);
        setPageSize(pageSize);
    };

    // 处理客户搜索 - 添加防抖机制
    const handleCustomerSearch = (value) => {
        // 清除之前的计时器
        if (customerSearchTimer.current) {
            clearTimeout(customerSearchTimer.current);
        }
        
        // 设置新的计时器，300ms后执行搜索
        customerSearchTimer.current = setTimeout(() => {
            setSearchName(value);
            setCurrentPage(1);
        }, 300); // 300ms防抖
    };

    // 产品列表操作
    const addProduct = () => {
        const newKey = Date.now().toString();
        // 添加新产品行时初始化其搜索状态
        setBomSearchState(prev => ({
            ...prev,
            [newKey]: {
                keyword: '',
                results: [],
                loading: false
            }
        }));
        
        const newProduct = {
            key: newKey,
            product_part_number: '',
            specification_and_model: '',
            quantity: 1
        };
        setProductList([...productList, newProduct]);
    };

    const removeProduct = (key) => {
        if (productList.length <= 1) {
            message.warning('至少保留一项产品信息');
            return;
        }
        // 移除产品行时同时清除其搜索状态
        const newState = {...bomSearchState};
        delete newState[key];
        setBomSearchState(newState);
        
        // 清除该产品行的防抖计时器
        if (debounceTimers.current[key]) {
            clearTimeout(debounceTimers.current[key]);
            delete debounceTimers.current[key];
        }
        
        setProductList(productList.filter(item => item.key !== key));
    };

    // 处理产品料号选择
    const handleProductPartNumberChange = (key, selectedNumber) => {
        // 从当前行的搜索结果中查找选中的BOM
        const currentSearchState = bomSearchState[key] || {};
        const selectedBom = currentSearchState.results.find(bom => bom.number === selectedNumber) || {};
        
        setProductList(productList.map(item => {
            if (item.key === key) {
                return { 
                    ...item, 
                    product_part_number: selectedNumber,
                    specification_and_model: selectedBom.specificationAndModel || ''
                };
            }
            return item;
        }));
    };

    // 处理数量变化
    const handleQuantityChange = (key, quantity) => {
        setProductList(productList.map(item => {
            if (item.key === key) {
                return { ...item, quantity };
            }
            return item;
        }));
    };

    // 文件上传验证
    const handleBeforeUpload = (fileType) => (file) => {
        const isPDF = file.type === 'application/pdf';
        const isWord = file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const isLt20M = file.size / 1024 / 1024 < 20;

        if (!isPDF && !isWord && !isExcel) {
            notification.error({ message: '仅支持PDF、Word和Excel文件格式' });
            return false;
        }
        
        if (!isLt20M) {
            notification.error({ message: '文件大小不能超过20MB' });
            return false;
        }

        if (fileType === 'business_contract') {
            setBusinessContractFile(file);
        } else {
            setTechnicalAgreementFile(file);
        }
        return false
    }

    // 表单提交
    const submit = async () => {
        try {
            const values = await form.validateFields()
            
            const hasInvalidProduct = productList.some(item => 
                !item.product_part_number
            );
            if (hasInvalidProduct) {
                notification.error({ message: '请为所有产品选择产品料号' });
                return;
            }

            // 计算产品总数量
            const totalQuantity = productList.reduce((sum, item) => sum + (item.quantity || 0), 0);
            
            // 检查总数量是否超过100台
            if (totalQuantity > 100) {
                // 弹出确认对话框
                Modal.confirm({
                    title: '数量确认',
                    content: `您输入的产品总数量为 ${totalQuantity} 台，超过了100台。请确认是否输入正确？`,
                    okText: '确认正确',
                    cancelText: '返回修改',
                    onOk: () => proceedWithSubmit(values, totalQuantity),
                });
                return;
            }
            
            // 直接提交
            proceedWithSubmit(values, totalQuantity);
            
        } catch (errorInfo) {
            notification.error({ message: "请检查填写信息是否有误" })
            setUploading(false);
        }
    }

    // 继续提交订单的逻辑
    const proceedWithSubmit = (values) => {

        const formData = new FormData()
        setUploading(true)
        
        formData.append('order_id', values.order_id)
        formData.append('contract_number', values.contract_number)
        formData.append('customer_id', values.customer_id)
        
        // 仅在money有有效值时才添加到formData
        if (values.money !== undefined && values.money !== null && values.money !== '' && values.money > 0) {
            formData.append('money', values.money)
        }
        
        if (values.order_date) {
            formData.append('order_date', dayjs(values.order_date).format('YYYY-MM-DD'));
        }
        
        if (values.quality_guarantee_date) {
            formData.append('quality_guarantee_date', dayjs(values.quality_guarantee_date).format('YYYY-MM-DD'));
        }

        if (values.remark) {
            formData.append('remark', values.remark);
        }

        formData.append('product_list', JSON.stringify(productList));

        if (technicalUploadType === 'file' && technicalAgreementFile) {
            formData.append('technical_agreement', technicalAgreementFile);
        } else if (technicalUploadType === 'reference' && values.technical_agreement_reference) {
            formData.append('technical_agreement_reference', values.technical_agreement_reference);
        }

        if (businessUploadType === 'file' && businessContractFile) {
            formData.append('business_contract', businessContractFile);
        } else if (businessUploadType === 'reference' && values.business_contract_reference) {
            formData.append('business_contract_reference', values.business_contract_reference);
        }

        fetch("/admin/sales/uploadOrder", {
            method: "POST",
            body: formData,
            headers:{
                Authorization: `Bearer ${JSON.parse(localStorage.getItem('user')).token}`
            }
        }).then(response => response.json())
          .then(data => {
              if(data.code === 200) {
                  notification.success({ message: "上传成功" })
                  form.resetFields();
                  setBusinessContractFile(null);
                  setTechnicalAgreementFile(null);
                  setProductList([
                      { key: '1', product_part_number: '', specification_and_model: '', quantity: 1 }
                  ]);
              } else {
                  notification.error({ message: data.msg || "上传失败" })
              }
              setTimeout(()=>{ setUploading(false) },300)
          })
    }

    // 产品列表列定义
    const productColumns = [
        {
            title: '产品料号',
            dataIndex: 'product_part_number',
            key: 'product_part_number',
            width: '35%',
            render: (text, record) => {
                const searchState = bomSearchState[record.key] || {
                    keyword: '',
                    results: [],
                    loading: false
                };
                
                return (
                    <Select
                        value={text}
                        onChange={(value) => handleProductPartNumberChange(record.key, value)}
                        onSearch={(keyword) => searchFirstLevelBoms(record.key, keyword)}
                        placeholder="输入产品编号搜索"
                        style={{ width: '100%' }}
                        showSearch
                        filterOption={false}
                        notFoundContent={searchState.loading ? <Spin size="small" /> : '无匹配的BOM'}
                    >
                        {searchState.results.map(bom => (
                            <Select.Option key={bom.number} value={bom.number}>
                                {`${bom.number} - ${bom.productName}`}
                            </Select.Option>
                        ))}
                    </Select>
                );
            }
        },
        {
            title: '规格型号',
            dataIndex: 'specification_and_model',
            key: 'specification_and_model',
            width: '35%',
            render: (text) => (
                <Input
                    value={text}
                    placeholder="选择产品料号后自动填充"
                    maxLength={100}
                    showCount
                    style={{ width: '100%' }}
                    disabled
                />
            )
        },
        {
            title: '产品数量',
            dataIndex: 'quantity',
            key: 'quantity',
            width: '20%',
            render: (text, record) => (
                <InputNumber
                    min={1}
                    precision={0}
                    value={text}
                    onChange={(value) => handleQuantityChange(record.key, value)}
                    style={{ width: '100%' }}
                    placeholder="数量"
                />
            )
        },
        {
            title: '操作',
            key: 'action',
            width: '10%',
            render: (_, record) => (
                <Button 
                    type="text" 
                    danger 
                    icon={<MinusOutlined />} 
                    onClick={() => removeProduct(record.key)}
                    size="small"
                />
            )
        }
    ];

    // 标签样式
    const labelStyle = {
        fontSize: '0.9rem',
        fontWeight: 500,
        color: '#333',
        whiteSpace: 'nowrap',
        paddingRight: '8px'
    };

    return (
        <div style={{ 
            height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "auto",
            backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute",  
            color: "white", fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                <div style={{
                    fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", 
                    display: "flex", textIndent: "1rem", justifyContent: "flex-start", 
                    alignContent: "flex-start", flexWrap: "wrap",
                    paddingBottom: "2vh"
                }}>
                    <Button type="primary" onClick={toExcel} style={{marginTop:"2vh"}}>
                        <IconFont type="icon-Excel" />通过excel表格导入
                    </Button>
                    <Divider/>
                    <Form
                        style={{ marginTop: "2vh", width: "95%" }}
                        form={form}
                        labelCol={{ span: 8 }}
                        wrapperCol={{ span: 16 }}
                        labelAlign="right"
                    >
                        {/* 表单字段修改：添加合同编号，调整质保日期 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="订单号"
                                    name="order_id"
                                    rules={[{ required: true, message: '订单号不能为空' }]}
                                    labelStyle={labelStyle}
                                >
                                    <Input maxLength={50} showCount placeholder='请输入订单号' />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="合同编号"
                                    name="contract_number"
                                    rules={[{ required: true, message: '合同编号不能为空' }]}
                                    labelStyle={labelStyle}
                                >
                                    <Input maxLength={50} showCount placeholder='请输入合同编号' />
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="所属客户"
                                    name="customer_id"
                                    rules={[{ required: true, message: '请选择所属客户' }]}
                                    labelStyle={labelStyle}
                                >
                                    <Select
                                        showSearch
                                        placeholder="请选择客户"
                                        style={{ width: '100%' }}
                                        onSearch={handleCustomerSearch}
                                        filterOption={false}
                                        notFoundContent={loadingCustomers ? <Spin size="small" /> : '无客户数据'}
                                        value={form.getFieldValue('customer_id')}
                                        onChange={(value) => form.setFieldValue('customer_id', value)}
                                    >
                                        {customerList.map(customer => (
                                            <Select.Option key={customer.id} value={customer.id}>
                                            {customer.name}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                    
                                    <Pagination
                                        current={currentPage}
                                        pageSize={pageSize}
                                        total={totalCustomers}
                                        onChange={handlePageChange}
                                        showSizeChanger
                                        disabled={loadingCustomers}
                                        size="small"
                                        style={{ fontSize: '0.85rem' }}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                {/* 添加金额字段 */}
                                <Form.Item
                                    label="订单金额"
                                    name="money"
                                    rules={[
                                        { type: 'number', min: 0.01, message: '订单金额必须大于0' }
                                    ]}
                                    labelStyle={labelStyle}
                                >
                                    <InputNumber
                                        min={0.01}
                                        max={999999999999}
                                        step={0.01}
                                        precision={2}
                                        style={{ width: '100%' }}
                                        formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                                        parser={value => value.replace(/¥\s?|(,*)/g, '')}
                                        placeholder="请输入订单金额"
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="订单日期"
                                    name="order_date"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <DatePicker placeholder='请选择订单日期' />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label="质保日期"
                                    name="quality_guarantee_date"
                                    rules={[{ required: false }]}  // 修改为非必填
                                    labelStyle={labelStyle}
                                >
                                    <DatePicker placeholder='请选择质保日期（非必填）' />
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        {/* 产品列表区域 */}
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item
                                    label="产品列表"
                                    labelStyle={{...labelStyle, display: 'block', marginBottom: '1rem'}}
                                    labelCol={{ span: 24 }}
                                    wrapperCol={{ span: 24 }}
                                >
                                    <div style={{ marginBottom: 16, border: '1px solid #e8e8e8', borderRadius: '4px' }}>
                                        <Table
                                            columns={productColumns}
                                            dataSource={productList}
                                            pagination={false}
                                            bordered={false}
                                            locale={{ emptyText: '请添加产品信息' }}
                                            scroll={{ x: 'max-content' }}
                                        />
                                        
                                        <Button 
                                            type="dashed" 
                                            onClick={addProduct} 
                                            style={{ width: '100%', marginTop: 16 }}
                                            icon={<PlusOutlined />}
                                        >
                                            添加产品
                                        </Button>
                                    </div>
                                </Form.Item>
                            </Col>
                        </Row>
                        
                        {/* 其他表单内容保持不变 */}
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item
                                    label="特殊备注"
                                    name="remark"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Input maxLength={100} showCount placeholder='请输入特殊备注' />
                                </Form.Item>
                            </Col>
                        </Row>

                        <Row>
                            <Col span={24}>
                                <h3 style={{ margin: '16px 0', color: '#1890ff', borderLeft: '3px solid #1890ff', paddingLeft: 12, fontSize: '1.1rem' }}>附件上传</h3>
                            </Col>
                        </Row>
                    
                        <Row gutter={24}>
                            {/* 技术协议上传区域 */}
                            <Col span={12}>
                                <Form.Item
                                    label="技术协议上传方式"
                                    name="technical_upload_type"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Radio.Group 
                                        value={technicalUploadType}
                                        onChange={e => setTechnicalUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {technicalUploadType === 'file' && (
                                    <Form.Item
                                        label="技术协议文件"
                                        name="technical_agreement"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('technical_agreement')}
                                            onRemove={() => {
                                                setTechnicalAgreementFile(null);
                                                return true;
                                            }}
                                            fileList={technicalAgreementFile ? [{
                                                uid: technicalAgreementFile.uid || Date.now().toString(),
                                                name: technicalAgreementFile.name,
                                                status: 'done'
                                            }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {technicalUploadType === 'reference' && (
                                    <Form.Item
                                        label="技术协议引用单号"
                                        name="technical_agreement_reference"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>

                            {/* 商务合同上传区域 */}
                            <Col span={12}>
                                <Form.Item
                                    label="商务合同上传方式"
                                    name="business_upload_type"
                                    rules={[{ required: false }]}
                                    labelStyle={labelStyle}
                                >
                                    <Radio.Group 
                                        value={businessUploadType}
                                        onChange={e => setBusinessUploadType(e.target.value)}
                                        buttonStyle="solid"
                                        style={{ width: '100%' }}
                                    >
                                        <Radio.Button value="file" icon={<UploadOutlined />} style={{ flex: 1 }}>直接上传文件</Radio.Button>
                                        <Radio.Button value="reference" icon={<LinkOutlined />} style={{ flex: 1 }}>引用单号</Radio.Button>
                                    </Radio.Group>
                                </Form.Item>

                                {businessUploadType === 'file' && (
                                    <Form.Item
                                        label="商务合同文件"
                                        name="business_contract"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Upload
                                            maxCount={1}
                                            beforeUpload={handleBeforeUpload('business_contract')}
                                            onRemove={() => {
                                                setBusinessContractFile(null);
                                                return true;
                                            }}
                                            fileList={businessContractFile ? [{
                                                uid: businessContractFile.uid || Date.now().toString(),
                                                name: businessContractFile.name,
                                                status: 'done'
                                            }] : []}
                                        >
                                            <Button icon={<UploadOutlined />}>选择文件</Button>
                                        </Upload>
                                    </Form.Item>
                                )}

                                {businessUploadType === 'reference' && (
                                    <Form.Item
                                        label="商务合同引用单号"
                                        name="business_contract_reference"
                                        rules={[{ required: false }]}
                                        labelStyle={labelStyle}
                                    >
                                        <Input maxLength={50} showCount placeholder='请输入要引用的单号' />
                                    </Form.Item>
                                )}
                            </Col>
                        </Row>
                    
                        <Row>
                            <Col span={24} style={{ marginTop: 16 }}>
                                <Button type="primary" onClick={submit}>提交订单</Button>
                            </Col>
                        </Row>
                    </Form>
                    
                    {/* 上传加载模态框 */}
                    <Modal
                        open={uploading}
                        centered
                        closable={false}
                        footer={null}
                        maskClosable={false}
                        width={400}
                        bodyStyle={{ textAlign: 'center', padding: '30px 20px' }}
                    >
                        <Spin/>
                        <div style={{ marginTop: 20, fontSize: 16, fontWeight: 'bold', color: '#333' }}>
                            上传中
                        </div>
                        <div style={{ marginTop: 10, color: '#666' }}>
                            请勿关闭页面或进行其他操作
                        </div>
                    </Modal>
                </div>
            </div>
        </div>
    )
}

export default UploadOrder

var styles = {
    kshcontainer: {
        width: "98%", 
        height: "95%", 
        position: "absolute", top: "3%", 
        left: "1%", backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
        boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
        overflow: "scroll"
    },
}
    